package controllers
{
	import flash.external.ExternalInterface;

	/**
	 *
	 * @author Pamakids-Chita
	 *
	 */
	public class ZhugeAnalytics
	{
		private static var _instance:ZhugeAnalytics
		public static function  get instance():ZhugeAnalytics 
		{
			return _instance ||= new ZhugeAnalytics;
		}

		public function ZhugeAnalytics()
		{
		}

		public var currentView:String;
		public var currentKey:String;

		public function identify(id:String,obj:Object):void
		{
			return;
			ExternalInterface.call('zhuge.identify',id,obj);
		}

		public function trackView(key:String,value:String,record:Boolean=false):void
		{
			var obj:Object = {};
			obj[key] = value;
			currentKey = key;
			currentView = value;

			if(record)
				track('页面选择',obj);
		}

		public function track(eventName:String,obj:Object,needView:Boolean=false):void
		{
			return;
			if(needView)
				obj = mergeObj(obj,{'位置':currentView});
			ExternalInterface.call('zhuge.track',eventName,obj);

			var str:String=eventName+'\n'+JSON.stringify(obj)+'\n';
			ExternalInterface.call('traceEvent',str);
		}

		private function mergeObj(o1:Object,o2:Object):Object
		{
			if(o2)
				for  (var i:String in o2) 
					if(o2[i])
						o1[i]=o2[i]
			return o1
		}

		private function getDateObj(d:Date):Object
		{
			var newDate:Date =  new Date(d.getTime());
			trace("EventTracer.getDateObj(d)",JSON.stringify(newDate)
				,newDate.getFullYear()+"-"+format(newDate.getUTCMonth()+1)+"-"+format(newDate.getUTCDate())+"T"+format(newDate.getUTCHours())+":"+format(newDate.getUTCMinutes())+":"+format(newDate.getUTCSeconds())+"."+format(newDate.getUTCMilliseconds(),3)+"Z");
			return {
					"__type": "Date",
					"iso": newDate.getFullYear()+"-"+format(newDate.getUTCMonth()+1)+"-"+format(newDate.getUTCDate())+"T"+format(newDate.getUTCHours())+":"+format(newDate.getUTCMinutes())+":"+format(newDate.getUTCSeconds())+"."+format(newDate.getUTCMilliseconds(),3)+"Z"
				}
		}
		private function format(num:uint,length:int=2):String
		{
			var nStr:String = num.toString();
			var len:int = length - nStr.length;
			var result:String="";
			if(len > 0)
				for (var i:int = 0; i < len; i++)
					result+="0"
			result +=nStr;
			return result;
		}
	}
}


